package com.mgy.example.dao.config.db;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

import java.util.Map;

/**
 * mybatis配置
 *
 * @author mgy
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@MapperScan(basePackages = "com.mgy.example.dao.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class MybatisConfig {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis.config-location}")
    private String configLocation;


    @Bean
    public CustomRoutingDataSource routingDataSource(@Qualifier("dataSourceMap") Map<Object, Object> dataSourceMap) {
        CustomRoutingDataSource customRoutingDataSource = new CustomRoutingDataSource();
        customRoutingDataSource.setDefaultDataSource(dataSourceMap.get(-1));
        customRoutingDataSource.setDataSources(dataSourceMap);
        return customRoutingDataSource;
    }


    @Bean
    public LazyConnectionDataSourceProxy dataSourceProxy(CustomRoutingDataSource routingDataSource) {
        LazyConnectionDataSourceProxy dataSourceProxy = new LazyConnectionDataSourceProxy();
        dataSourceProxy.setTargetDataSource(routingDataSource);
        return dataSourceProxy;
    }


    /**
     * 需要手动配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactitonManager(LazyConnectionDataSourceProxy dataSourceProxy) {
        return new DataSourceTransactionManager(dataSourceProxy);
    }

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory(LazyConnectionDataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceProxy);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource(configLocation));
        Interceptor[] plugins = {new MybatisInterceptor()};
        bean.setPlugins(plugins);
        return bean.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
